﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using QLVatTu.Class;
using QLVatTu.InPhieu;

namespace QLVatTu.NghiepVu
{
    public partial class frmQuanLyChuyenKho : Form
    {
        public frmQuanLyChuyenKho()
        {
            InitializeComponent();
        }

        KetNoiDB cn = new KetNoiDB();

        private void btnThem_Click(object sender, EventArgs e)
        {
            frmThemPhieuChuyen frm = new frmThemPhieuChuyen();
            frm.ShowDialog();
            load_dtgPhieuChuyen();
        }

        private void btnThoat_Click(object sender, EventArgs e)
        {
            if (TopLevel == false) this.Parent.Parent.Controls.Remove(this.Parent);
            else this.Close();
        }

        private void load_dtgPhieuChuyen(string dieuKien = null)
        {
            string sql = "";
            if (dieuKien != null)
            {
                sql = @"SELECT    dbo.tbl_ChuyenKho.MaChuyenKho, dbo.tbl_ChuyenKho.TuKho, dbo.tbl_ChuyenKho.DenKho, dbo.tbl_ChuyenKho.NguoiChuyen, dbo.tbl_ChuyenKho.NgayChuyen, 
                                  dbo.tbl_ChuyenKho.DienGiai, XacNhan = case XacNhan when '0' then N'Chưa xác nhận' when '1' then N'Đã xác nhận' end
                        FROM         dbo.tbl_ChuyenKho INNER JOIN
                                     dbo.tbl_Kho ON dbo.tbl_ChuyenKho.TuKho = dbo.tbl_Kho.MaKho
                        "
                        + dieuKien;
            }
            else
            {
                sql = @"SELECT     dbo.tbl_ChuyenKho.MaChuyenKho, dbo.tbl_ChuyenKho.TuKho, dbo.tbl_ChuyenKho.DenKho, dbo.tbl_ChuyenKho.NguoiChuyen, dbo.tbl_ChuyenKho.NgayChuyen, 
                                   dbo.tbl_ChuyenKho.DienGiai, XacNhan = case XacNhan when '0' then N'Chưa xác nhận' when '1' then N'Đã xác nhận' end
                        FROM         dbo.tbl_ChuyenKho INNER JOIN
                                     dbo.tbl_Kho ON dbo.tbl_ChuyenKho.TuKho = dbo.tbl_Kho.MaKho
                        ";
            }
            DataTable tbl = cn.getTable(sql);
            dtgPhieuChuyen.DataSource = tbl;
        }

        private void loadData()
        {
            cbbKhoXuat.DataSource = cn.getTable("select * from tbl_Kho");
            cbbKhoXuat.DisplayMember = "TenKho";
            cbbKhoXuat.ValueMember = "MaKho";

            cbbKhoNhap.DataSource = cn.getTable("select * from tbl_Kho");
            cbbKhoNhap.DisplayMember = "TenKho";
            cbbKhoNhap.ValueMember = "MaKho";

            colKhoChuyen.DataSource = cn.getTable("select * from tbl_Kho");
            colKhoChuyen.DisplayMember = "TenKho";
            colKhoChuyen.ValueMember = "MaKho";

            colKhoNhan.DataSource = cn.getTable("select * from tbl_Kho");
            colKhoNhan.DisplayMember = "TenKho";
            colKhoNhan.ValueMember = "MaKho";

            load_dtgPhieuChuyen();
        }

        private void frmQuanLyChuyenKho_Load(object sender, EventArgs e)
        {
            if (cn.KetNoi())
            {
                loadData();
            }
        }

        private void dtgPhieuChuyen_SelectionChanged(object sender, EventArgs e)
        {
            if (dtgPhieuChuyen.SelectedRows.Count > 0 && dtgPhieuChuyen.CurrentRow.Cells["colMaPhieuChuyen"].Value != null)
            {
                string sql = @"SELECT   row_number() over(order by tbl_ChiTietChuyenKho.MaChuyenKho) as STT, dbo.tbl_ChiTietChuyenKho.MaVatTu, dbo.tbl_VatTu.TenVatTu, dbo.tbl_ChiTietChuyenKho.MaDonViTinh, dbo.tbl_DonViTinh.TenDonViTinh, 
                                                          dbo.tbl_ChiTietChuyenKho.SoLuong, dbo.tbl_ChiTietChuyenKho.SoLuongTon
                                    FROM         dbo.tbl_DonViTinh INNER JOIN
                                                          dbo.tbl_ChiTietChuyenKho ON dbo.tbl_DonViTinh.MaDonViTinh = dbo.tbl_ChiTietChuyenKho.MaDonViTinh INNER JOIN
                                                          dbo.tbl_VatTu ON dbo.tbl_ChiTietChuyenKho.MaVatTu = dbo.tbl_VatTu.MaVatTu
                                    WHERE     dbo.tbl_ChiTietChuyenKho.MaChuyenKho = '" + dtgPhieuChuyen.CurrentRow.Cells["colMaPhieuChuyen"].Value.ToString() + "'";
                DataTable tbl = cn.getTable(sql);
                dtgChiTiet.DataSource = tbl;

                sql = "select XacNhan from tbl_ChuyenKho where MaChuyenKho='"+dtgPhieuChuyen.CurrentRow.Cells["colMaPhieuChuyen"].Value.ToString()+"'";
                bool _XacNhan = bool.Parse(cn.LayDuLieu(sql));
                btnXacNhan.Enabled = !_XacNhan;
            }
           
        }

        private void btnSua_Click(object sender, EventArgs e)
        {
            if (dtgPhieuChuyen.SelectedRows.Count > 0 && dtgPhieuChuyen.CurrentRow.Cells["colMaPhieuChuyen"].Value != null)
            {
                frmThemPhieuChuyen frm = new frmThemPhieuChuyen();
                frm.MaPhieuChuyen = dtgPhieuChuyen.CurrentRow.Cells["colMaPhieuChuyen"].Value.ToString();
                frm.ShowDialog();
                load_dtgPhieuChuyen();
            }
        }

        private void btnXoa_Click(object sender, EventArgs e)
        {
            if (dtgPhieuChuyen.RowCount == 0) return;
            DialogResult msg = MessageBox.Show("Bạn chắc chắn muốn xóa?", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (msg == DialogResult.Yes)
            {
                cn.Delete_Table("tbl_ChiTietChuyenKho", "MaChuyenKho='" + dtgPhieuChuyen.CurrentRow.Cells["colMaPhieuChuyen"].Value.ToString() + "'");
                cn.Delete_Table("tbl_LuuKho", "SoPhieu='" + dtgPhieuChuyen.CurrentRow.Cells["colMaPhieuChuyen"].Value.ToString() + "'");
                cn.Delete_Table("tbl_ChuyenKho", "MaChuyenKho='" + dtgPhieuChuyen.CurrentRow.Cells["colMaPhieuChuyen"].Value.ToString() + "'");
                MessageBox.Show("Xóa thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                MessageBox.Show("Xóa không thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            load_dtgPhieuChuyen();
        }

        private void ckbSoPhieu_CheckedChanged(object sender, EventArgs e)
        {
            if (ckbSoPhieu.Checked == true)
            {
                txtSoPhieu.Text = "";
                txtSoPhieu.Enabled = true;
            }
            else
            {
                txtSoPhieu.Text = "Tìm theo số phiếu";
                txtSoPhieu.Enabled = false;
            }
        }

        private void ckbKhoXuat_CheckedChanged(object sender, EventArgs e)
        {
            if (ckbKhoXuat.Checked == true)
            {
                cbbKhoXuat.Enabled = true;
            }
            else
            {
                ckbKhoXuat.Enabled = false;
            }
        }

        private void ckbNguoiLap_CheckedChanged(object sender, EventArgs e)
        {
            if (ckbNguoiLap.Checked == true)
            {
                txtNguoiXuat.Text = "";
                txtNguoiXuat.Enabled = true;
            }
            else
            {
                txtNguoiXuat.Text = "Tìm theo người lập phiếu";
                txtNguoiXuat.Enabled = false;
            }
        }

        private void ckbNgayXuat_CheckedChanged(object sender, EventArgs e)
        {
            if (ckbNgayXuat.Checked == true)
            {
                dtipTuNgay.Enabled = true;
                dtipDenNgay.Enabled = true;
            }
            else
            {
                dtipTuNgay.Enabled = false;
                dtipDenNgay.Enabled = false;
            }
        }

        private string XacDinhDieuKienLoc()
        {
            string dienKienLoc = "where 1=1";

            if (ckbSoPhieu.Checked == true && txtSoPhieu.Text.Trim() != "")
            {
                dienKienLoc += "and MaChuyenKho like '%" + txtSoPhieu.Text.Trim() + "%'";
            }

            if (ckbKhoXuat.Checked == true && cbbKhoXuat.Items.Count > 0)
            {
                dienKienLoc += "and TuKho='" + cbbKhoXuat.SelectedValue.ToString() + "'";
            }

            if (ckbKhoNhap.Checked == true && cbbKhoNhap.Items.Count > 0)
            {
                dienKienLoc += "and DenKho='" + cbbKhoNhap.SelectedValue.ToString() + "'";
            }

            if (ckbNguoiLap.Checked == true && txtNguoiXuat.Text.Trim() != "")
            {
                dienKienLoc += "and NguoiChuyen like '%" + txtNguoiXuat.Text.Trim() + "%'";
            }

            if (ckbNgayXuat.Checked == true)
            {
                dienKienLoc += "and NgayChuyen between '" + dtipTuNgay.Value.ToString() + "' and '" + dtipDenNgay.Value.ToString() + "'";
            }

            return dienKienLoc;
        }

        private void btnTimKiem_Click(object sender, EventArgs e)
        {
            load_dtgPhieuChuyen(XacDinhDieuKienLoc());
        }

        private void ckbKhoNhap_CheckedChanged(object sender, EventArgs e)
        {
            if (ckbKhoNhap.Checked == true)
            {
                cbbKhoNhap.Enabled = true;
            }
            else
            {
                cbbKhoNhap.Enabled = false;
            }
        }

        private void btnLuu_Click(object sender, EventArgs e)
        {
            frmInPhieuChuyen frm = new frmInPhieuChuyen();
            if (dtgPhieuChuyen.SelectedRows.Count > 0 && dtgPhieuChuyen.CurrentRow.Cells["colMaPhieuChuyen"].Value != null)
            {
                string MaPhieuChuyen = dtgPhieuChuyen.CurrentRow.Cells["colMaPhieuChuyen"].Value.ToString();
                List<PhieuChuyenKho> list = new List<PhieuChuyenKho>();
                string Ngay = "";
                string Thang = "";
                string Nam = "";
                string NguoiChuyen = "";
                string KhoChuyen = "";
                string KhoNhap = "";
                string DienGiai = "";
                string HangMuc = "";

                string sql = "";
                sql = @"SELECT     dbo.tbl_ChuyenKho.DenKho, dbo.tbl_Kho.TenKho, dbo.tbl_ChuyenKho.NguoiChuyen, dbo.tbl_ChuyenKho.NgayChuyen, dbo.tbl_ChuyenKho.DienGiai,tbl_LoaiPhieu.TenLoaiPhieu
                        FROM         dbo.tbl_ChuyenKho INNER JOIN
                                              dbo.tbl_Kho ON dbo.tbl_ChuyenKho.TuKho = dbo.tbl_Kho.MaKho INNER JOIN dbo.tbl_LoaiPhieu ON dbo.tbl_ChuyenKho.MaLoaiPhieu = dbo.tbl_LoaiPhieu.MaLoaiPhieu
                        WHERE     dbo.tbl_ChuyenKho.MaChuyenKho = '" + MaPhieuChuyen + "'";
                DataTable tbl = cn.getTable(sql);
                if (tbl.Rows.Count > 0)
                {
                    sql = @"SELECT     dbo.tbl_Kho.TenKho
                            FROM         dbo.tbl_ChuyenKho INNER JOIN
                                                  dbo.tbl_Kho ON dbo.tbl_ChuyenKho.DenKho = dbo.tbl_Kho.MaKho
                            WHERE     dbo.tbl_ChuyenKho.MaChuyenKho = '" + MaPhieuChuyen + "' AND dbo.tbl_ChuyenKho.DenKho = '" + tbl.Rows[0]["DenKho"].ToString() + "'";
                    string dataTenKho = cn.LayDuLieu(sql);

                    string NgayXuat = tbl.Rows[0]["NgayChuyen"].ToString();
                    DateTime dtNgayXuat = DateTime.Parse(NgayXuat);
                    Ngay = dtNgayXuat.Day.ToString();
                    Thang = dtNgayXuat.Month.ToString();
                    Nam = dtNgayXuat.Year.ToString();
                    NguoiChuyen = tbl.Rows[0]["NguoiChuyen"].ToString();
                    KhoChuyen = tbl.Rows[0]["TenKho"].ToString();
                    KhoNhap = dataTenKho;
                    DienGiai = tbl.Rows[0]["DienGiai"].ToString();
                    HangMuc = tbl.Rows[0]["TenLoaiPhieu"].ToString();
                }

                sql = @"SELECT  row_number() over(order by tbl_ChiTietChuyenKho.MaChuyenKho) as STT,  dbo.tbl_ChiTietChuyenKho.MaVatTu, dbo.tbl_VatTu.TenVatTu, dbo.tbl_DonViTinh.TenDonViTinh, dbo.tbl_ChiTietChuyenKho.SoLuong
                        FROM         dbo.tbl_ChiTietChuyenKho INNER JOIN
                                              dbo.tbl_DonViTinh ON dbo.tbl_ChiTietChuyenKho.MaDonViTinh = dbo.tbl_DonViTinh.MaDonViTinh INNER JOIN
                                              dbo.tbl_VatTu ON dbo.tbl_ChiTietChuyenKho.MaVatTu = dbo.tbl_VatTu.MaVatTu
                        where tbl_ChiTietChuyenKho.MaChuyenKho='" + MaPhieuChuyen + "'";
                DataTable dataChiTietChuyen = cn.getTable(sql);
                int stt = 0;
                if (dataChiTietChuyen.Rows.Count > 0)
                {
                    foreach (DataRow dr in dataChiTietChuyen.Rows)
                    {
                        stt++;
                        PhieuChuyenKho pck = new PhieuChuyenKho();
                        pck.MaPhieuChuyen = MaPhieuChuyen;
                        pck.Ngay = Ngay;
                        pck.Thang = Thang;
                        pck.Nam = Nam;
                        pck.NguoiChuyen = NguoiChuyen;
                        pck.KhoChuyen = KhoChuyen;
                        pck.KhoNhap = KhoNhap;
                        pck.DienGiai = DienGiai;

                        pck.STT = stt.ToString();
                        pck.MaVT = dr["MaVatTu"].ToString();
                        pck.TenVatTu = dr["TenVatTu"].ToString();
                        pck.DVT = dr["TenDonViTinh"].ToString();
                        pck.HangMuc = HangMuc;
                        pck.SL = dr["SoLuong"].ToString();
                        list.Add(pck);
                    }
                }
                frm.phieuChuyenKhoBindingSource.DataSource = list;
                frm.ShowDialog();
            }
        }

        private void btnXacNhan_Click(object sender, EventArgs e)
        {
            if (dtgPhieuChuyen.SelectedRows.Count > 0 && dtgPhieuChuyen.CurrentRow.Cells["colMaPhieuChuyen"].Value != null)
            { 
                    foreach (DataGridViewRow dgvr in dtgChiTiet.Rows)
                    {
                        if (dgvr.IsNewRow) continue;

                        string TuKho = "";
                        string DenKho = "";
                        string sql = "select TuKho,DenKho,NgayChuyen from tbl_ChuyenKho where MaChuyenKho='" + dtgPhieuChuyen.CurrentRow.Cells["colMaPhieuChuyen"].Value.ToString() + "'";
                        DataTable dt = cn.getTable(sql);
                        if (dt.Rows.Count > 0)
                        {
                            TuKho = dt.Rows[0]["TuKho"].ToString();
                            DenKho = dt.Rows[0]["DenKho"].ToString();
                        }
                        string MaVatTu = dgvr.Cells["colMaVatTu"].Value.ToString();
                        string MaDonViTinh = dgvr.Cells["colMaDonViTinh"].Value.ToString();

                        float SoLuong = 0;
                        SoLuong = float.Parse(dgvr.Cells["colSoLuong"].Value.ToString());
                        float SoLuongChuyen = -SoLuong;

                        sql = "select sum(SoLuong) as SoLuongTonKho from tbl_LuuKho where MaKho='" + TuKho + "' and MaVatTu='" + MaVatTu + "'";
                        string strSoLuongTon = cn.LayDuLieu(sql);
                        float SoLuongTon = 0;
                        if (strSoLuongTon != null && strSoLuongTon != "" && float.Parse(strSoLuongTon) >= 0) SoLuongTon = float.Parse(strSoLuongTon);

                        if (SoLuongTon < SoLuong)
                        {
                            MessageBox.Show("Không thể xác nhận phiếu.", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }
                        else
                        {
                            DialogResult msg = MessageBox.Show("Sau khi xác nhận bạn không thể sửa và xóa phiếu!", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                            if (msg == DialogResult.Yes)
                            {
                                cn.Update_Table("tbl_ChuyenKho", "XacNhan=1", "MaChuyenKho='" + dtgPhieuChuyen.CurrentRow.Cells["colMaPhieuChuyen"].Value.ToString() + "'");
                                cn.Insert_Table("tbl_LuuKho", "[SoPhieu],[MaKho],[MaVatTu],[SoLuong],[SoLuongPhePham],[NgayCapNhat]", "'" + dtgPhieuChuyen.CurrentRow.Cells["colMaPhieuChuyen"].Value.ToString() + "','" + TuKho + "','" + MaVatTu + "','" + SoLuongChuyen + "',0,'" + dtgPhieuChuyen.CurrentRow.Cells["colNgayChuyen"].Value.ToString() + "'");
                                cn.Insert_Table("tbl_LuuKho", "[SoPhieu],[MaKho],[MaVatTu],[SoLuong],[SoLuongPhePham],[NgayCapNhat]", "'" + dtgPhieuChuyen.CurrentRow.Cells["colMaPhieuChuyen"].Value.ToString() + "','" + DenKho + "','" + MaVatTu + "','" + SoLuong + "',0,'" + dtgPhieuChuyen.CurrentRow.Cells["colNgayChuyen"].Value.ToString() + "'");
                            }
                        }
                    }
            }
            load_dtgPhieuChuyen();
        }
    }
}
